/* eslint-disable camelcase */
// 封装axios
import axios, { AxiosError } from 'axios'
import { getToken, setToken } from './storage'
import history from '@/utils/history'
import { Toast } from 'antd-mobile'
import store from '@/store'
const baseURL = 'http://geek.itheima.net/v1_0/'
const instance = axios.create({
  baseURL,
  timeout: 5000
})

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    const token = getToken().token
    if (token) {
      // if (!config.headers) return
      // config.headers.Authorization = 'Bearer ' + token
      config.headers!.Authorization = 'Bearer ' + token
    }

    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    return response
  },
  async function (error: AxiosError<{message: string}>) {
    // 对请求错误做些什么
    if (!error.response) {
      Toast.show('网络异常')
      return Promise.reject(error)
    }
    if (error.response.status !== 401) {
      Toast.show('后端错误')
      return Promise.reject(error)
    }
    const { refresh_token } = getToken()
    if (!refresh_token) {
      // alert('refresh_token')
      history.replace('/login', { from: history.location.pathname })
      Toast.show('登录信息过期')
      return Promise.reject(error)
    }
    try {
      // 使用refresh_token去换取新token
      // 使用 axios 来发送请求
      const res = await axios.put(`${baseURL}authorizations`, null, {
        headers: {
          Authorization: `Bearer ${refresh_token}`
        }
      })
      const newTokenInfo = { token: res.data.data.token, refresh_token }
      // 保存新token
      setToken(newTokenInfo)
      // redux
      store.dispatch({
        type: 'login/token',
        payload: newTokenInfo
      })

      // 重发请求
      return instance(error.config)
    } catch (err) {
      history.push({
        pathname: '/login',
        state: { from: history.location.pathname }
      })
      return Promise.reject(error)
    }
  }
)

export default instance
